#!/usr/bin/env python
# encoding: utf-8

import urllib
import urllib2
import sys
import json
from qa.interface.app.parameters import encryption, ia_http, ia_json
import base64
import os
import hashlib
import platform

from urllib2 import Request, urlopen, URLError, HTTPError
import ssl


def get_token(acc, pas):
    if platform.platform().split('-')[0] == 'Darwin':
            ssl._create_default_https_context = ssl._create_unverified_context
    pc = encryption.prpcrypt()
    dev_id = pc.get_devid()
    if acc[0] == "+":
        values = {'type': 'mobile', 'identity': acc, 'password': pas, 'dev_id': dev_id}
    else:
        values = {'type': 'email', 'identity': acc, 'password': pas, 'dev_id': dev_id}
    jdata2 = pc.jiami_j2j(values)
    req = urllib2.Request(url='http://106.75.100.161' + '/passport/auth', data=jdata2, headers=addHeader(0))
    token = ''

    try:
        response = urllib2.urlopen(req)
        the_page = response.read()
        j2 = pc.jiemi_j2j(the_page)

        j3 = json.loads(j2)

        token = j3['access_token']
        uid = j3['uid']
        if token != '':
            en_text = pc.encrypt(token)
            ak_text = pc.padAK(en_text)
            b2 = base64.encodestring(str(uid) + ':' + ak_text).replace('\n', '')
            # save_auth('Basic '+b2)
            return 'Basic ' + b2
        else:
            return 0

    except HTTPError, e:
        # print 'get token from server error'+e.read()
        result = e.read()
        result = eval(result)
        return 0, result["code"]
    except URLError, e:
        print e.reason
        print 'get error'
        return 0


def get_token_forzhuce():
    phttp = ia_http.py_http()
    pc = encryption.prpcrypt()
    pjson = ia_json.py_json()

    values = {'type': 'mobile', 'stage': 'token'}
    # jdata2=pc.jiami_j2j(values)
    jdata2 = pc.jiami_j2j(values)
    jdata2 = json.loads(jdata2)
    page = phttp.http_read(ia_configure.url_ym + ia_configure.zc_identity, addHeader(0), 10, jdata2)
    values = pc.jiemi_j2j(page)
    values = pjson.json_load(values)
    a = pjson.json_getvalue(values, 'token')
    # b=pjson.json_getvalue(values,'captcha')
    return a


def addHeader(b_int, acc='', pas='', num=''):
    header = {}
    header['Accept-Language'] = 'zh-cn'
    # header['User-Agent']='Mozilla/5.0 (iPhone; iOS 9.3.1; Scale/2.00) iOS/%s (Asia/Shanghai)'%ia_configure.head
    header[
        'User-Agent'] = 'Mozilla/5.0 (Linux; U; Android 6.0.1; SM-N9200 Build/MMB29K) Android/020305_2.3.5_0652_0441 (Asia/Shanghai) Dalvik/2.1.0 app/1'
    header['Content-Type'] = 'application/json'
    header['Host'] = 'pay-test.blued.cn'
    header['Connection'] = 'keep-alive'
    header['Accept'] = '*/*'
    if b_int != 0:
        auth = get_token(acc, pas)
        if auth[0] == 0:
            return auth
        else:
            header['Authorization'] = auth
            save_auth(header, num)
            return header
    else:
        save_auth_no(header)
        return header


def save_auth(text, num):
    text = str(text)
    if num == 1:
        f = open('auth.txt', 'w')
    else:
        f = open('vice_auth.txt', 'w')
    f.write(text)
    f.close()


def save_auth_no(text):
    text = str(text)
    f = open('auth_no.txt', 'w')
    f.write(text)
    f.close()


def get_auth(num):
    if num == 1:
        file = 'auth.txt'
    else:
        file = 'vice_auth.txt'
    if os.path.exists(file):
        f = open(file, 'r')
        auth = f.read()
        f.close()
        return auth


# def get_auth_no():
#     if os.path.exists('auth_no.txt'):
#         f=open('auth_no.txt','r')
#         auth=f.read()
#         f.close()
#         return auth



















def im_token(acc, pas):
    if platform.platform().split('-')[0] == 'Darwin':
            ssl._create_default_https_context = ssl._create_unverified_context
    pc = encryption.prpcrypt()
    dev_id = pc.get_devid()
    if acc[0] == "+":
        values = {'type': 'mobile', 'identity': acc, 'password': pas, 'dev_id': dev_id}
    else:
        values = {'type': 'email', 'identity': acc, 'password': pas, 'dev_id': dev_id}
    jdata2 = pc.jiami_j2j(values)
    req = urllib2.Request(url='http://106.75.100.161' + '/passport/auth', data=jdata2, headers=addHeader(0))
    token = ''

    try:
        response = urllib2.urlopen(req)
        the_page = response.read()
        j2 = pc.jiemi_j2j(the_page)
        j3 = json.loads(j2)
        token = j3['access_token']
        uid = j3['uid']
        if token != '':
            en_text = pc.encrypt(token)
            ak_text = pc.padAK(en_text)
            b2 = base64.encodestring(str(uid) + ':' + ak_text).replace('\n', '')
            # save_auth('Basic '+b2)
            return j3, 'Basic ' + b2
        else:
            return 0

    except HTTPError, e:
        # print 'get token from server error'+e.read()
        result = e.read()
        # print result
        result = eval(result)
        return 0, result["code"]
    except URLError, e:
        print e.reason
        print 'get error'
        return 0


def im_addHeader(b_int, acc='', pas='', num=''):
    header = {}
    header['Accept-Language'] = 'zh-cn'
    header[
        'User-Agent'] = 'Mozilla/5.0 (Linux; U; Android 5.1.1; SM-N9200 Build/LMY47X) Android/%s (Asia/Shanghai) Dalvik/2.1.0'
    header['Content-Type'] = 'application/json'
    header['Connection'] = 'keep-alive'
    header['Accept'] = '*/*'
    if b_int != 0:
        auth = im_token(acc, pas)
        header['Authorization'] = auth[1]
        if auth[0] != 0:
            return auth[0], header
        else:
            return auth[1], header
    else:
        save_auth_no(header)
        return header
